<!-- Aside 侧边栏 -->
<script setup lang="ts">
import type { ConversationItem } from 'vue-element-plus-x/types/Conversations';
import type { ChatSessionVo } from '@/api/session/types';
import { ChatDotRound, ChatLineRound, Delete, Loading, ShoppingCart, View } from '@element-plus/icons-vue';
import { useRoute, useRouter } from 'vue-router';
import { get_session } from '@/api';
import SvgIcon from '@/components/SvgIcon/index.vue';
import { SIDE_BAR_WIDTH } from '@/config/index';
import { useCollapseToggle } from '@/hooks/useCollapseToggle';
import { useScreenStore } from '@/hooks/useScreen';
import Collapse from '@/layouts/components/Header/components/Collapse.vue';
import { useDesignStore } from '@/stores';
import { useSessionStore } from '@/stores/modules/session';

const logo = 'https://www.xqnmz.com/static/image/default.jpg';

const route = useRoute();
const router = useRouter();
const designStore = useDesignStore();
const sessionStore = useSessionStore();
const { isMobile } = useScreenStore();
const { changeCollapse } = useCollapseToggle();

// 侧边栏切换函数（与Collapse组件保持一致）
function handleChangeCollapse() {
  changeCollapse();
  // 每次切换折叠状态，重置安全区状态
  designStore.isSafeAreaHover = false;
  // 重置首次激活悬停状态
  designStore.hasActivatedHover = false;
  if (!designStore.isCollapse) {
    document.documentElement.style.setProperty(`--sidebar-left-container-default-width`, `${SIDE_BAR_WIDTH}px`);
  }
  else {
    document.documentElement.style.setProperty(`--sidebar-left-container-default-width`, ``);
  }
}

const sessionId = computed(() => route.params?.id);
const conversationsList = computed(() => sessionStore.sessionList);
const loadMoreLoading = computed(() => sessionStore.isLoadingMore);
const active = ref<string | undefined>();

onMounted(async () => {
  // 手机版默认关闭侧边栏 - 直接设置关闭状态
  if (isMobile.value && !designStore.isCollapse) {
    designStore.isCollapse = true;
    designStore.isSafeAreaHover = false;
    designStore.hasActivatedHover = false;
    document.documentElement.style.setProperty(`--sidebar-left-container-default-width`, ``);
  }

  // 获取会话列表
  await sessionStore.requestSessionList();
  // 打印 conversationsList 内容

  // 高亮最新会话
  if (conversationsList.value.length > 0 && sessionId.value) {
    const currentSessionRes = await get_session(`${sessionId.value}`);
    // 通过 ID 查询详情，设置当前会话 (因为有分页)
    sessionStore.setCurrentSession(currentSessionRes.data);
  }
});

watch(
  () => sessionStore.currentSession,
  (newValue) => {
    active.value = newValue ? `${newValue.id}` : undefined;
  },
);

// 创建会话
function handleCreatChat() {
  // 创建会话, 跳转到默认聊天
  sessionStore.createSessionBtn();

  // 手机版点击新会话时触发侧边栏折叠
  if (isMobile.value) {
    handleChangeCollapse();
  }
}

// 切换会话
function handleChange(item: ConversationItem<ChatSessionVo>) {
  sessionStore.setCurrentSession(item);
  router.replace({
    name: 'chatWithId',
    params: {
      id: item.id,
    },
  });

  // 手机版点击会话时触发侧边栏折叠
  if (isMobile.value) {
    handleChangeCollapse();
  }
}

// 处理组件触发的加载更多事件
async function handleLoadMore() {
  if (!sessionStore.hasMore)
    return; // 无更多数据时不加载
  await sessionStore.loadMoreSessions();
}

// 清空所有会话
async function handleClearAllSessions() {
  try {
    await ElMessageBox.confirm('确定要清空所有会话吗？此操作不可恢复。', '清空会话', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger',
      cancelButtonClass: 'el-button--info',
      roundButton: true,
      autofocus: false,
    });

    await sessionStore.clearAllSessions();
  }
  catch (error) {
    // 用户取消操作
  }
}

// 鼠标悬停清空按钮
function handleClearBtnHover() {
  // 可以添加悬停效果逻辑
}

// 鼠标离开清空按钮
function handleClearBtnLeave() {
  // 可以添加离开效果逻辑
}

// 套餐购买
function handlePackagePurchase() {
  // 跳转到套餐购买页面
  window.open('https://www.xqnmz.com/plugin.php?id=dzlab_qwenai&mod=buy', '_blank');
}

// 切换护眼模式
function toggleEyeProtectionMode() {
  designStore.setEyeProtectionMode(!designStore.eyeProtectionMode);
}

// 右键菜单
function handleMenuCommand(command: string, item: ConversationItem<ChatSessionVo>) {
  switch (command) {
    case 'delete':
      ElMessageBox.confirm('删除后，聊天记录将不可恢复。', '确定删除对话？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger',
        cancelButtonClass: 'el-button--info',
        roundButton: true,
        autofocus: false,
      })
        .then(() => {
          // 删除会话
          sessionStore.deleteSessions([item.id!]);
          nextTick(() => {
            if (item.id === active.value) {
              // 如果删除当前会话 返回到默认页
              sessionStore.createSessionBtn();
            }
          });
        })
        .catch(() => {
          // 取消删除
        });
      break;
    case 'rename':
      ElMessageBox.prompt('', '编辑对话名称', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputErrorMessage: '请输入对话名称',
        confirmButtonClass: 'el-button--primary',
        cancelButtonClass: 'el-button--info',
        roundButton: true,
        inputValue: (item as any).sessionTitle, // 设置默认值
        autofocus: false,
        inputValidator: (value) => {
          if (!value) {
            return false;
          }
          return true;
        },
      }).then(({ value }) => {
        sessionStore
          .updateSession({
            id: item.id!,
            sessionTitle: value,
            sessionContent: (item as any).sessionContent,
          } as any)
          .then((res) => {
            if (res?.code == 200) {
              ElMessage({
                type: 'success',
                message: '修改成功',
              });
              nextTick(() => {
                // 如果是当前会话，则更新当前选中会话信息
                if (sessionStore.currentSession?.id === item.id) {
                  sessionStore.setCurrentSession({
                    ...item,
                    sessionTitle: value,
                  } as any);
                }
              });
            }
          })
          .catch((_) => {
            // 如果请求失败，不显示成功消息

            ElMessage({
              type: 'error',
              message: '修改失败，请稍后重试',
            });
          });
      });
      break;
    default:
      break;
  }
}
</script>

<template>
  <div
    class="aside-container"
    :class="{
      'aside-container-suspended': designStore.isSafeAreaHover,
      'aside-container-collapse': designStore.isCollapse,
      // 折叠且未激活悬停时添加 no-delay 类
      'no-delay': designStore.isCollapse && !designStore.hasActivatedHover,
    }"
  >
    <div class="aside-wrapper">
      <div v-if="!designStore.isCollapse" class="aside-header">
        <div class="flex items-center gap-8px hover:cursor-pointer" @click="handleCreatChat">
          <el-image :src="logo" alt="logo" fit="cover" class="logo-img" />
          <span class="logo-text max-w-150px text-overflow">麻醉AI助手</span>
        </div>
        <Collapse class="ml-auto" />
      </div>

      <div class="aside-body">
        <div class="creat-chat-btn-wrapper">
          <div class="creat-chat-btn" @click="handleCreatChat">
            <el-icon class="add-icon">
              <Plus />
            </el-icon>
            <span class="creat-chat-text">新对话</span>
            <SvgIcon name="ctrl+k" size="37" class="ctrl-k-icon" />
          </div>
        </div>

        <div class="aside-content">
          <!-- 加载状态 -->
          <div v-if="sessionStore.isLoading" class="h-full flex-center">
            <div class="loading-container">
              <el-icon class="loading-icon">
                <Loading />
              </el-icon>
            </div>
          </div>

          <!-- 有数据时显示会话列表 -->
          <div v-else-if="conversationsList.length > 0" class="conversations-wrap overflow-hidden">
            <!-- 会话列表标题栏 -->
            <div class="conversation-group-title">
              <div class="title-content">
                <el-icon class="title-icon">
                  <ChatDotRound />
                </el-icon>
                <span class="title-text">会话列表</span>
                <span class="session-count">{{ conversationsList.length }}</span>
              </div>
              <!-- 清空会话按钮 -->
              <div
                v-if="conversationsList.length > 0"
                class="clear-sessions-btn"
                @click="handleClearAllSessions"
                @mouseenter="handleClearBtnHover"
                @mouseleave="handleClearBtnLeave"
              >
                <el-icon class="clear-icon">
                  <Delete />
                </el-icon>
              </div>
            </div>
            <Conversations
              v-model:active="active"
              :items="conversationsList"
              :label-max-width="200"
              :show-tooltip="true"
              :tooltip-offset="60"
              show-built-in-menu
              row-key="id"
              label-key="sessionTitle"
              tooltip-placement="right"
              :load-more="handleLoadMore"
              :load-more-loading="loadMoreLoading"
              :items-style="{
                marginLeft: '8px',
                userSelect: 'none',
                borderRadius: '10px',
                padding: '8px 12px',
              }"
              :items-active-style="{
                backgroundColor: '#fff',
                boxShadow: '0 1px 2px rgba(0, 0, 0, 0.05)',
                color: 'rgba(0, 0, 0, 0.85)',
              }"
              :items-hover-style="{
                backgroundColor: 'rgba(0, 0, 0, 0.04)',
              }"
              @menu-command="handleMenuCommand"
              @change="handleChange"
            >
              <template #label="{ item }">
                <el-icon :class="`conversation-prefix-icon ${item.digest ? ' digest' : ''}`">
                  <ChatLineRound />
                </el-icon>
                <div class="conversation-label-container">
                  <span :class="`conversation-label ${item.digest ? ' digest' : ''}`">
                    {{ item.sessionTitle }}
                  </span>
                </div>
              </template>
            </Conversations>
          </div>

          <!-- 无数据时显示空状态 -->
          <el-empty v-else class="h-full flex-center" description="暂无对话记录" />
        </div>

        <!-- 底部按钮组 - 并排显示 -->
        <div class="bottom-buttons-wrapper">
          <div class="buttons-row">
            <!-- 护眼模式按钮 -->
            <div class="eye-protection-wrapper">
              <el-button
                :type="designStore.eyeProtectionMode ? 'success' : 'default'"
                size="default"
                class="eye-protection-btn"
                @click="toggleEyeProtectionMode"
              >
                <el-icon class="mr-2">
                  <View />
                </el-icon>
                {{ designStore.eyeProtectionMode ? '关闭护眼' : '护眼模式' }}
              </el-button>
            </div>

            <!-- 套餐购买按钮 -->
            <div class="package-purchase-wrapper">
              <el-button
                type="primary"
                size="default"
                class="package-purchase-btn"
                @click="handlePackagePurchase"
              >
                <el-icon class="mr-2">
                  <ShoppingCart />
                </el-icon>
                套餐购买
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
// 基础样式
.aside-container {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 11;
  width: var(--sidebar-default-width);
  height: 100%;
  pointer-events: auto;
  background-color: var(--sidebar-background-color);
  border-right: 0.5px solid var(--s-color-border-tertiary, rgb(0 0 0 / 8%));
  .aside-wrapper {
    display: flex;
    flex-direction: column;
    height: 100%;

    // 侧边栏头部样式
    .aside-header {
      display: flex;
      align-items: center;
      height: 36px;
      margin: 10px 12px 0;
      .logo-img {
        box-sizing: border-box;
        width: 36px;
        height: 36px;
        padding: 4px;
        overflow: hidden;
        background-color: #ffffff;
        border-radius: 50%;
        img {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
        }
      }
      .logo-text {
        font-size: 16px;
        font-weight: 700;
        color: rgb(0 0 0 / 85%);
        transform: skewX(-2deg);
      }
    }

    // 侧边栏内容样式
    .aside-body {
      display: flex;
      flex-direction: column;
      flex: 1;
      min-height: 0;

      .creat-chat-btn-wrapper {
        padding: 0 12px;
        .creat-chat-btn {
          display: flex;
          gap: 6px;
          align-items: center;
          padding: 8px 6px;
          margin-top: 16px;
          margin-bottom: 6px;
          color: #0057ff;
          cursor: pointer;
          user-select: none;
          background-color: rgb(0 87 255 / 6%);
          border: 1px solid rgb(0 102 255 / 15%);
          border-radius: 12px;
          &:hover {
            background-color: rgb(0 87 255 / 12%);
          }
          .creat-chat-text {
            font-size: 14px;
            font-weight: 700;
            line-height: 22px;
          }
          .add-icon {
            width: 24px;
            height: 24px;
            font-size: 16px;
          }
          .svg-icon {
            height: 24px;
            margin-left: auto;
            color: rgb(0 87 255 / 30%);
          }
        }
      }

      .aside-content {
        display: flex;
        flex: 1;
        flex-direction: column;
        height: calc(100% - 80px); // 为底部按钮预留空间
        min-height: 0;

        // 会话列表高度-基础样式
        .conversations-wrap {
          height: 100%;
          .label {
            display: flex;
            align-items: center;
            height: 100%;
          }
        }
      }

      // 底部按钮组样式 - 并排显示
      .bottom-buttons-wrapper {
        margin-top: auto; // 推到最底部
        margin-bottom: 16px;

        .buttons-row {
          display: flex;
          gap: 8px;
          padding: 0 12px;

          // 护眼模式按钮样式
          .eye-protection-wrapper {
            flex: 1;

            .eye-protection-btn {
              width: 100%;
              height: 40px;
              background: #2a2a2a;
              border: 1px solid #404040;
              border-radius: 12px;
              color: #d9d9d9;
              font-weight: 500;
              transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

              &:hover {
                background: #3a3a3a;
                border-color: #505050;
                transform: translateY(-1px);
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
              }

              &:active {
                transform: translateY(0);
                box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
              }

              // 护眼模式激活状态
              &.el-button--success {
                background: #1a3a1a;
                border-color: #2a5a2a;
                color: #aaffaa;

                &:hover {
                  background: #2a4a2a;
                  border-color: #3a6a3a;
                }
              }
            }
          }

          // 套餐购买按钮样式
          .package-purchase-wrapper {
            flex: 1;

            .package-purchase-btn {
              width: 100%;
              height: 40px;
              background: linear-gradient(135deg, #0057ff, #3385ff);
              border: none;
              border-radius: 12px;
              box-shadow: 0 2px 8px rgba(0, 87, 255, 0.3);
              transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

              &:hover {
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(0, 87, 255, 0.4);
              }

              &:active {
                transform: translateY(0);
                box-shadow: 0 2px 6px rgba(0, 87, 255, 0.3);
              }
            }
          }
        }
      }
    }
  }
}

// 折叠样式
.aside-container-collapse {
  position: absolute;
  top: 54px;
  z-index: 22;
  height: auto;
  max-height: calc(100% - 110px);
  padding-bottom: 12px;
  overflow: hidden;

  /* 禁用悬停事件 */
  pointer-events: none;
  border: 1px solid rgb(0 0 0 / 8%);
  border-radius: 15px;
  box-shadow:
    0 10px 20px 0 rgb(0 0 0 / 10%),
    0 0 1px 0 rgb(0 0 0 / 15%);
  opacity: 0;

  // 指定样式过渡

  // 向左偏移一个宽度
  transform: translateX(-100%);
  transition: opacity 0.3s ease 0.3s, transform 0.3s ease 0.3s;

  /* 新增：未激活悬停时覆盖延迟 */
  &.no-delay {
    transition-delay: 0s, 0s;
  }
}

// 悬停样式
.aside-container-collapse:hover,
.aside-container-collapse.aside-container-suspended {
  height: auto;
  max-height: calc(100% - 110px);
  padding-bottom: 12px;
  overflow: hidden;
  pointer-events: auto;
  border: 1px solid rgb(0 0 0 / 8%);
  border-radius: 15px;
  box-shadow:
    0 10px 20px 0 rgb(0 0 0 / 10%),
    0 0 1px 0 rgb(0 0 0 / 15%);

  // 直接在这里写悬停时的样式（与 aside-container-suspended 一致）
  opacity: 1;

  // 过渡动画沿用原有设置
  transform: translateX(15px);
  transition: opacity 0.3s ease 0s, transform 0.3s ease 0s;

  // 会话列表高度-悬停样式
  .conversations-wrap {
    height: calc(100vh - 155px) !important;
  }
}

// 样式穿透
:deep() {
  // 会话列表背景色
  .conversations-list {
    background-color: transparent !important;
    margin-bottom: 60px !important; // 为底部购买按钮预留空间

    .conversation-label {
      font-size: 14px;
      color: #303133;
      position: relative;
      white-space: nowrap;
      width: 180px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: inline-block;
    }
    .digest {
      color: #3385ff!important;
    }
    .conversation-prefix-icon {
      margin-right: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  // 群组标题样式 - 调整为更低调的样式
  .conversation-group-title {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px !important;
    margin: 8px 12px 4px;
    background: rgba(0, 0, 0, 0.02) !important;
    border: 1px solid rgba(0, 0, 0, 0.06);
    border-radius: 8px;
    .title-content {
      display: flex;
      align-items: center;
      gap: 6px;

      .title-icon {
        width: 14px;
        height: 14px;
        font-size: 14px;
        color: #666;
      }

      .title-text {
        font-size: 13px;
        font-weight: 500;
        color: #666;
      }

      .session-count {
        display: flex;
        align-items: center;
        justify-content: center;
        min-width: 18px;
        height: 16px;
        padding: 0 4px;
        font-size: 10px;
        font-weight: 600;
        color: #fff;
        background: linear-gradient(135deg, #0057ff, #3385ff);
        border-radius: 9px;
        box-shadow: 0 2px 4px rgba(0, 87, 255, 0.3);
      }
    }

    // 清空会话按钮
    .clear-sessions-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 28px;
      height: 28px;
      color: #999;
      cursor: pointer;
      border-radius: 8px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

      &:hover {
        color: #ff4d4f;
        transform: translateY(-1px);
      }

      .clear-icon {
        width: 16px;
        height: 16px;
        font-size: 16px;
        transition: transform 0.2s ease;
      }

      &:hover .clear-icon {
        transform: scale(1.1);
      }
    }
  }
}

.eye-protection-mode{
    .conversation-label {
      color: #ffffff;
    }
  }
// Loading 样式
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  height: 200px;

  .loading-icon {
    font-size: 28px;
    color: #0057ff;
    animation: spin 1.5s linear infinite;
    filter: drop-shadow(0 2px 4px rgba(0, 87, 255, 0.2));
  }

  .loading-text {
    font-size: 14px;
    font-weight: 500;
    color: #666;
    letter-spacing: 0.5px;
    animation: pulse 2s ease-in-out infinite;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
    opacity: 1;
  }
  50% {
    transform: rotate(180deg);
    opacity: 0.8;
  }
  100% {
    transform: rotate(360deg);
    opacity: 1;
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.02);
  }
}

// 响应式优化
@media (max-width: 768px) {
  .loading-container {
    gap: 12px;

    .loading-icon {
      font-size: 24px;
    }

    .loading-text {
      font-size: 13px;
    }
  }

  // 手机版下隐藏ctrl+k图标
  .ctrl-k-icon {
    display: none !important;
  }
  .conversation-label {
    font-size: 15px!important;
  }

}
</style>
